package spike.s003.sqlflow;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import spike.s003.sqlflow.entity.CourseEntity;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by ylyang on 04/04/2017.
 */
@Service
public class MasterCourseService {
    private Logger logger = Logger.getLogger(MasterCourseService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static Map<String, CourseEntity> courseMap;

    public Map<String, CourseEntity> obtainCourseMap() {
        Map<String, CourseEntity> map = courseMap;

        if (null == map) {
            logger.info("***");
            logger.info("START LOAD COURSE MASTER DATA.");
            List<CourseEntity> entities = jdbcTemplate.query("select * from s003_courses", new CourseEntity.BeanRowMapper());
            map = entities.stream().collect(Collectors.toMap(e -> e.getCourseID(), e -> e));
            courseMap = map;
            logger.info("FINISH LOAD COURSE MASTER DATA.");
            logger.info("***");
        }

        return map;
    }

    public CourseEntity accessCourseByID(String courseID) {
        return obtainCourseMap().get(courseID);
    }
}
